#!/usr/bin/env ./jshost


var input_text="test...";
var message="";
var number=1;

var ech=function(x){ return "echo('"+x+"')" };
var inp=function(x){ return "inp('"+x+"')" };


var sync=function(x){ return [ ech(number), inp(input_text) ].join(";\n")};

var input=function(x){ input_text=x };


var rec=function(){
	number=Math.random();
	setTimeout(rec,3000);
};
rec();



var box=function(){
};




var doit=function(fd){
	var headers=[];
	var buf=[];
	var headers_sent=!1;
	var dirty=false;
	
	var flush=function(){
		if(!dirty)
			return;
		if(!headers_sent && headers.length>0) {
			var i;
			for(i=0;i<headers.length;++i)
				write(fd, headers[i]+"\n");
			write(fd, "\n");
			headers_send=true;
			headers=[];
		}	
		if(buf.length>0) {
			write(fd, buf.join(""));
			buf=[];
		}
		dirty=false;
	};
	var header=function(x){
		headers[headers.length]=x;
		dirty=true;
	};
	var echo=function(x){
		buf[buf.length]=x;
		dirty=true;
		flush();
	};
	
	var request_headers=read(fd).split(/\r?\n/);
	var GET=decodeURI(request_headers[0].match(/GET \/([^ \?]*)/i)[1]);
	var result;
	try{
		result=eval(GET);
	} catch(e){
		result="ERROR: "+e.message;
	}
//	result=unescape((""+result).replace(/\\(u[0-9a-f]{4})/g, "%$1"));

	write(fd, "HTTP/1.1 200 OK\r\n");
	header("Content-Type: text/plain; charset=UTF-8");
	header("Cache-Control: no-store, no-cache, must-revalidate");
	echo(result);

	return;
};

var onrequest=function(fd){return doit(fd)};


start_httpserver(false);
